import { defineStore } from 'pinia';

interface ITodo {
  id: number;
  content: string;
  done: boolean;
}

const useTodosStore = defineStore('todos', {
  state: () => {
    return {
      list: JSON.parse(localStorage.getItem('Pinia-todos-list') || '[]') as ITodo[],
    };
  },
  actions: {
    changeDone(id: number) {
      const todo = this.list.find(v => v.id === id);
      if (todo) todo.done = !todo.done;
    },
    delTodo(id: number) {
      this.list = this.list.filter(v => v.id !== id);
    },
    addTodo(content: string) {
      if (this.list.find(v => v.content === content.trim())) return alert('不能重复添加相同任务');
      const todo = { id: Date.now(), content, done: false };
      this.list.unshift(todo);
    },
    checkedAllTodos() {
      this.list.forEach(v => (v.done = !this.isCheckedAll));
    },
  },
  getters: {
    todoCount(): number {
      return this.list && this.list.length;
    },
    isCheckedAll(): boolean {
      return this.list.length > 0 && this.list.every(v => v.done);
    },
  },
});

export default useTodosStore;
